<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, onBeforeRouteLeave } from 'vue-router';
const router = useRouter();
const { currentRoute } = useRouter();
import { ElMessage, ElMessageBox } from 'element-plus'; // 修改记录
import * as echarts from 'echarts';
import openLayer from "@/components/common/openlayer.vue"
import ShadeImg from "@/components/common/shadeImg.vue";
import ewm from '@/components/common/erweima.vue';
const custonEwm = ref(null);
const isshade = ref(false);
const moreImg = ref([]);
import { fungusInfo, fungusmediaAll, animediaAll, BaseData, resourcePoint, mediaDelete, uploadByResource, anvocalAll } from "@/utils/api.js"
import np from '@/assets/img/np.png'
import zwnr from '@/assets/img/zwnr.png'
import zwsj from '@/assets/img/zwsj.png'
import play from '@/assets/img/play.png'
import moment from 'moment'
const $moment = moment
defineExpose({
    $moment
})

// 详情
import imageCarousel from '@/components/common/imageCarousel.vue'
const islm = ref(false);
const ics = ref(null);

const sonO = reactive({
    id: currentRoute.value.query.id, fileTypes: ['image', 'video']
})

const openics = (item) => {
    if (item == 'iv') {
        sonO.fileTypes = ['image', 'video']
    }
    if (item == 'ws') {
        sonO.fileTypes = ['voice']
    }
    islm.value = true;
    // ics.value.getallm()
}

const redsic = () => {
    getanimediaAll();
    // getanvocalAll();
    islm.value = false;
}

// 详情 B

// 修改记录
import { EditPen, UploadFilled, Plus, Edit, View, Back, FolderAdd, Delete } from '@element-plus/icons-vue'	//导入Search图标
import haForm from '@/components/common/ha-form.vue';
import uploadIs from '@/components/common/uploadImage.vue';
import uploadMapImages from '@/components/common/uploadMapImage.vue';
import preVideo from '@/components/common/preVideo.vue';
import twavs from '@/assets/img/twavs.png'
import iconaudio from '@/assets/img/iconaudio.png'
import audiogif from '@/assets/img/audiogif.gif'
import dingwei from '@/assets/img/dingwei.png'
const audioPlayer = new Audio();
const lookVideo = ref(null)
const isaddp = ref(false);
const isShowp = ref(true);
const PointL = ref([])
const ruleFormRef = ref(null)
const ruleForm = reactive({
    lon: '',
    lat: '',
    altitude: 0
})

const rules = reactive({
    lon: [
        { required: true, message: '经度不能为空', trigger: 'blur' }
    ],
    lat: [
        { required: true, message: '经度不能为空', trigger: 'blur' }
    ],
    altitude: [
        { required: true, message: '海拔不能为空', trigger: 'blur' }
    ]
})

const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // uploadByResource
            const formData = new FormData();
            formData.append("file", '');
            formData.append("resourceId", currentRoute.value.query.id);
            formData.append("resourceType", 'fungus');
            formData.append("type", 2);
            formData.append("lon", ruleForm.lon);
            formData.append("lat", ruleForm.lat);
            formData.append("altitude", ruleForm.altitude);
            formData.append("identifyUser", '');
            uploadByResource(formData).then(res => {
                if (res.code == '200') {
                    ElMessage({
                        type: 'success',
                        message: '保存成功',
                    })
                    getresourcePoint();
                    setTimeout(function () {
                        ruleForm.lon = '';
                        ruleForm.lat = '';
                        ruleForm.altitude = 0;
                        ols.value.delIlayer('dgdgwgw5354bgdg')
                    }, 1000)
                } else {
                    ElMessage({
                        type: 'warning',
                        message: res.msg,
                    })
                }
            })
            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields();
    isaddp.value = false
}

const getllna = (item) => {
    // console.log(item);
    ruleForm.lon = item[0];
    ruleForm.lat = item[1];


    if (isaddp.value) {
        ols.value.previewshape([{
            id: 'hsfhfdh93qysdfbhtyrwe8bhf',
            name: '',
            borderColor: "",
            fillColor: '',
            offsetY: 24,
            iconSrc: dingwei,
            geojson: {
                'type': 'Point',
                'coordinates': item
            }
        }], 'dgdgwgw5354bgdg');
    }
}

const getresourcePoint = async () => {
    let res = await resourcePoint(currentRoute.value.query.id)
    let arrs = []
    if (res.code == '200') {
        arrs = res.data;
    }
    PointL.value = arrs;

    let arr = [];
    res.data.forEach((e, x) => {
        let z = {
            id: 'animalsidis' + x,
            name: `序号:${e.sortNumber}`,
            borderColor: "",
            fillColor: "",
            iconSrc: mapico,
            // data: {},
            geojson: { coordinates: [e.lon, e.lat], type: "Point" }
        }
        arr.push(z);
    })
    if (arr.length > 0) {
        setTimeout(function () {
            ols.value.previewshape(arr, 'hfsdhf859eu52');
        }, 1500)

    }
}

const del = (item) => {
    ElMessageBox.confirm(
        '确定要删除这条数据吗?',
        '消息提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {

            mediaDelete([item.id]).then((res) => {
                if (res.code == '200') {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    getresourcePoint();
                } else {
                    ElMessage({
                        type: 'warning',
                        message: res.msg,
                    })
                }
            })

        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}

// 上传
const uai = ref(null)
const umai = ref(null)
const uploadImgObj = ref({})

const customUpload = () => {
    let item = {
        typetx: "精彩照片",
        imgs: ode.wonderfulMedia,
        resourceId: currentRoute.value.query.id,
        resourceType: 'fungus',
        type: 0,
        lon: '',
        lat: '',
        altitude: '',
    }
    uai.value.open(item);
}

const customUploadm = (typetx, item) => {
    let data = {
        typetx: typetx,
        uploadType: item,
        resourceId: currentRoute.value.query.id,
        resourceType: 'fungus',
        type: 1,
        lon: '',
        lat: '',
        altitude: '',
    }
    umai.value.open(data);
}

const addsm = () => {
    ruleForm.lon = '';
    ruleForm.lat = '';
    ruleForm.altitude = 0;
    isaddp.value = true
};

const lookPoint = (item) => {
    ols.value.locationM([item.lon, item.lat]);
}

const xglna = (item) => {
    ruleForm.lon = item.lon;
    ruleForm.lat = item.lat;
    ruleForm.altitude = item.altitude;
    isaddp.value = true
}

// 上传 B

const haf = ref(null);
const optionObj = ref({
    gangs: [],
    kes: [],
    levels: [],
    mens: [],
    mus: [],
    shus: []
});

const allimg = ref([]);
let total = [];
let startIndex = 24; // 初始索引位置
const getanimediaAll = async () => {
    let params = {
        "resourceId": currentRoute.value.query.id,
        "fileTypes": [
            "image", 'video'
        ],
        "pageSize": 9999,
        "pageNum": 1,
        "sourceType": "",
        "time": "",
        "keywords": ""
    }
    let res = await animediaAll(params);
    if (res.code == '200') {
        total = res.data.content;
        allimg.value = total.slice(0, 24);

    } else {
        ElMessage({
            message: res.message,
            type: 'warning',
        })
        allimg.value = []
    }
}

const load = () => {
    startIndex += 24;
    const newItems = total.slice(startIndex, startIndex + 24);
    allimg.value = [...allimg.value, ...newItems];
}

const getBaseData = async () => {
    let data = await BaseData('fungus', usermsg.areaId, [], [], [], [], [], [])
    optionObj.value = data.data;
}

const redta = () => {
    getanimediaAll();
}
// 修改记录 B
const activeName = ref('first')
const ols = ref(null)

const handleClick = (tab, event) => {
    console.log(tab, event)
}
const goback = () => {
    router.go(-1)
}
const iscarousel = ref(false)

const ode = reactive({
    fungusResource: {},
    meidaData: [],
    vocalData: [],
    wonderfulMedia: []
})

import mapico from '@/assets/icon/zhenjunziyuananimal_anchor_bottom_center.png'

const getAnimalsInfo = async () => {
    let res = await fungusInfo(currentRoute.value.query.id);
    if (res.code == '200') {
        // 修改记录
        if (res.data.wonderfulMedia.length == 0) {
            let z = {
                type: "image",
                path: np
            }
            res.data.wonderfulMedia.push(z)
        }


        getBaseData();// 修改记录

        Object.assign(ode, res.data);
        iscarousel.value = true
        // let arr = [];
        // res.data.locationData.forEach((e, x) => {
        //     let z = {
        //         id: 'animalsidis' + x,
        //         name: '',
        //         borderColor: "",
        //         fillColor: "",
        //         iconSrc: mapico,
        //         data: {},
        //         geojson: { coordinates: [e[0], e[1]], type: "Point" }
        //     }
        //     arr.push(z);
        // })

        // if (arr.length > 0) {
        //     ols.value.previewshape(arr, 'hfsdhf859eu52');
        // }
    } else {
        ElMessage({
            message: res.message,
            type: 'warning',
        })
        list.value = []
    }
}

const filimg = (data) => {
    if (data.length == 0 || data == 'undefined') {
        return [np, np, np]
    } else {
        let arr = [];
        data.forEach(e => {
            arr.push(e.path);
        });
        return arr;
    }
};

const openpop = (data) => {
    moreImg.value = data;
    isshade.value = true
}
let usermsg = '';
onMounted(() => {
    // 修改记录
    usermsg = window.sessionStorage.getItem('usermsg');
    // console.log(usermsg);
    if (usermsg == undefined) {
        alert('您无权查看该网站，请登录后才能正常使用')
    } else {
        usermsg = JSON.parse(usermsg);
    };

    getAnimalsInfo();
    getanimediaAll();
    // getfungusmediaAll();
    // 修改记录
    getresourcePoint();
})

onBeforeRouteLeave((to, from, next) => {
    // 在进入路由之前执行的逻辑操作
    // 可以进行一些权限验证、数据加载等操作
    let oldPath = to.path.split('/');
    let newPath = from.path.split('/')[1];
    if (oldPath.indexOf(newPath) == -1) {
        window.sessionStorage.removeItem('fungus');
    }
    next()
});


</script>
<template>
    <div style="position: relative;" class="gradual">
        <!-- 修改记录 -->
        <div class="addt" style="border-bottom:1px solid rgba(56, 123, 255, 0.1) ;">
            <div>
                <span style="font-weight: 700;font-size: 18px;">物种详情</span>
            </div>
            <el-button @click.stop="goback" size="large" :icon="Back">返回</el-button>
        </div>
        <div class="dbx">
            <div class="Whitearea">
                <div class="ha-title">
                    <span>基础信息</span>
                </div>
                <div class="baseb">
                    <div class="baseb-left clearfix">
                        <div class="base-info">
                            <div>
                                <div class="bi-t-1">
                                    {{ ode.fungusResource.zhongPy }}
                                    <!-- 修改记录 -->
                                    <el-button type="info" plain :icon="EditPen" style="border:none; margin-left: 24px;"
                                        @click.stop="haf.openform(ode.animalsResource, '修改', 'fungus', optionObj)">
                                        修改
                                    </el-button>
                                    <el-button type="info" plain :icon="UploadFilled"
                                        style="border:none; margin-left: 24px;" @click.stop="customUpload">
                                        编辑精彩照片
                                    </el-button>
                                </div>
                                <div class="bi-t-3">
                                    <span class="bi-t-2">{{ ode.fungusResource.zhong }}</span>
                                    <span class="bi-t-4"
                                        v-if="ode.fungusResource.endangeredLevel != '' && ode.fungusResource.endangeredLevel">
                                        {{ ode.fungusResource.endangeredLevel }}
                                    </span>
                                    <span class="bi-t-5"
                                        v-if="ode.fungusResource.level != '' && ode.fungusResource.level">{{
                                            ode.fungusResource.level
                                        }}</span>
                                </div>
                                <div class="bi-t-6">
                                    <span style="color: #606266;">拉丁名</span>
                                    <span style="font-style: italic;font-size: 20px;margin-left: 16px;">{{
                                        ode.fungusResource.zhongLatinName }}</span>
                                </div>
                                <div class="bi-t-6">
                                    <span style="color: #606266;">英文名</span>
                                    <span style="font-style: italic;font-size: 20px;margin-left: 16px;">{{
                                        ode.fungusResource.zhongEn == null ? '--' :
                                            ode.fungusResource.zhongEn }}</span>
                                </div>
                            </div>
                            <div class="bi-t-7">
                                <div style="color: #606266;margin-bottom: 8px;">扫描二维码查看物种详情</div>
                                <el-image style="width: 130px; height: 130px" :src="ode.fungusResource.qrCodeUrl"
                                    :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                                    :preview-src-list="[ode.fungusResource.qrCodeUrl]" :initial-index="1" fit="cover" />
                            </div>
                        </div>

                        <div style="height: 16px;"></div>
                        <div class="ha-title">分布</div>
                        <div style="color: #333;line-height: 2;">{{ ode.fungusResource.distribution == '' ? '--' :
                            ode.fungusResource.distribution }}</div>
                        <div style="height: 16px;"></div>
                        <!-- <div class="ha-title">形态学特征</div>
                        <div style="color: #333;line-height: 2;">{{ ode.fungusResource.characteristic == '' ? '--' :
                            ode.fungusResource.characteristic }}</div> -->
                    </div>
                    <div class="baseb-right">
                        <el-carousel v-show="iscarousel" height="400px" style="width: 100%;overflow: hidden;"
                            indicator-position="none">
                            <el-carousel-item v-for="(item, index) in ode.wonderfulMedia" :key="'item' + index">
                                <div class="hsq-car">
                                    <el-image v-if="item.type == 'image'" style="width: 100%; height: 100%"
                                        :src="item.path" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                                        :preview-src-list="[item.path]" :initial-index="1" :preview-teleported="true"
                                        fit="cover" />

                                    <video v-else style="width: 100%;" :src="item.path" controls></video>
                                </div>
                            </el-carousel-item>
                        </el-carousel>
                    </div>
                </div>
            </div>

            <div style="height: 16px;"></div>
            <div class="Whitearea">
                <!-- 修改记录 -->
                <div class="addt">
                    <div style="display: flex;align-items: center;">
                        <span class="ha-title">照片/视频</span>
                        <el-button plain :icon="UploadFilled" style="border:none; margin-left: 24px;"
                            @click.stop="customUploadm('照片/视频', '照片')">
                            上传照片/视频
                        </el-button>
                    </div>

                    <span @click.stop="openics('iv')" style="color: #387BFF;cursor: pointer;">查看更多>></span>
                </div>

                <div class="de-mv">
                    <!-- 修改记录 -->
                    <template v-for="(i, index) in allimg" :key="i.id">
                        <div v-if="index < 6">
                            <el-image style="width: 100%;height: 175px;" :src="i.thumbnail" v-if="i.fileType == 'image'"
                                :zoom-rate="1.2" :preview-src-list="[i.mediaUrl]" :initial-index="index" />

                            <div @click.stop="lookVideo.open(i.mediaUrl)" style="height: 175px;" class="playlms"
                                v-if="i.fileType == 'video'">
                                <img style="width: 100%;height: 100%;" :src="i.converUrl" alt="">
                                <img style="width: 50px;height:50px;position: absolute;z-index: 2;" :src="play" alt="">
                            </div>


                            <div class="de-txt">
                                <div>
                                    <span>{{ i.sourceType }}</span>
                                    <span>{{ i.label }}</span>
                                </div>
                                <div style="color: #AAAAAA;">
                                    <span>@{{ i.identifyUser }}</span>
                                    <span>{{ $moment(i.time).format('YYYY-MM-DD') }}</span>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>


                <!-- 修改记录 -->
                <div v-if="allimg.length == 0" style="text-align: center;">
                    <img style="height: 200px" :src="zwnr" alt="">
                </div>
            </div>

            <div style="height: 16px;"></div>
            <div class="Whitearea">
                <div class="ha-title">
                    <span>保护区内发现情况</span>
                </div>
                <div class="chart-box">
                    <div style="width: 50%;display: flex;align-items: center;justify-content: center;">
                        <img :src="zwsj" alt="">
                    </div>
                    <div style="width: 50%;display: flex;align-items: center;justify-content: center;">
                        <img :src="zwsj" alt="">
                    </div>

                </div>
            </div>

            <div style="height: 16px;"></div>
            <div class="Whitearea">
                <div class="ha-title">
                    <span>保护区内分布情况</span>
                </div>
                <!-- <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                    <el-tab-pane label="点位分布" name="first">点位分布</el-tab-pane>
                    <el-tab-pane label="热力图" name="second">热力图</el-tab-pane>
                </el-tabs> -->
                <div class="map-box" style="position: relative;">
                    <div class="conter">
                        <div class="qzTitle">
                            <div></div>
                            <div>
                                <span>点位列表</span>
                            </div>
                            <div class="m-info-mit">
                                <el-switch v-model="isShowp" class="ml-2" inline-prompt
                                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: rgba(56, 123, 255, 1)"
                                    active-text="收起列表" inactive-text="展开列表" />
                                <el-button :icon="Plus" style="margin-left: 16px;" type="info" @click.stop="addsm"
                                    plain>添加点位</el-button>
                            </div>
                        </div>
                        <el-table v-show="isShowp" :data="PointL" height="500" style="width: 100%;margin-top: 16px;"
                            :header-cell-style="{ 'color': '#333', 'line-height': '40px' }">

                            <el-table-column label="序号" prop="sortNumber" width="60" show-overflow-tooltip />
                            <el-table-column label="经度" prop="lon" width="80" show-overflow-tooltip />
                            <el-table-column label="纬度" prop="lat" width="80" show-overflow-tooltip />
                            <el-table-column label="海拔" prop="altitude" width="60" show-overflow-tooltip />
                            <el-table-column label="操作" fixed="right" width="160">
                                <template #default="scope">
                                    <el-button type="info" title="查看" @click.stop="lookPoint(scope.row)" plain
                                        :icon="View" size="small">
                                        <!-- 查看 -->
                                    </el-button>
                                    <el-button type="info" title="修改" plain :icon="EditPen"
                                        @click.stop="xglna(scope.row)" size="small">
                                        <!-- 修改 -->
                                    </el-button>
                                    <el-button type="info" title="删除" @click.stop="del(scope.row)" plain :icon="Delete"
                                        size="small">
                                        <!-- 删除 -->
                                    </el-button>
                                </template>
                            </el-table-column>

                        </el-table>
                    </div>
                    <div class="addPoints" v-if="isaddp">
                        <div class="qzTitle">
                            <div></div>
                            <div>
                                <span>添加点位</span>
                                <span style="color: #E6A23C;margin-left: 8px;">(为保证位置正确，强烈建议点击地图选择点位位置)</span>
                            </div>

                        </div>
                        <div style="height: 16px;"></div>
                        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="top"
                            label-width="auto" class="demo-ruleForm" status-icon>
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="经度" prop="lon">
                                        <el-input v-model="ruleForm.lon" placeholder="格式示例：117.3306" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="纬度" prop="lat">
                                        <el-input v-model="ruleForm.lat" placeholder="格式示例： 40.568069" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="海拔" prop="altitude">
                                        <el-input type="number" v-model="ruleForm.altitude" />
                                    </el-form-item>
                                </el-col>

                            </el-row>


                            <el-form-item>
                                <el-button type="primary" style="background-color: #387BFF;color: #fff;"
                                    @click="submitForm(ruleFormRef)">
                                    确定添加
                                </el-button>
                                <el-button @click="resetForm(ruleFormRef)">结束添加</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                    <open-layer ref="ols" @PopUp="openpop" @send="getllna"></open-layer>
                </div>
            </div>
        </div>

        <!-- <div class="lkmr" v-if="islm">
            <div class="ha-title addt">
                <span>照片/视频</span>
                <el-button @click.stop="islm = false" size="default">返回</el-button>
            </div>

            <div class="de-mv imbx">
                <div v-for="i in allimg" :key="i.id">
                    <el-image style="width: 100%;height: 175px;" :src="i.thumbnail" v-if="i.fileType == 'image'"
                        :zoom-rate="1.2" :preview-src-list="[i.mediaUrl]" />
                    <div @click.stop="lookVideo.open(i.mediaUrl)" style="height: 175px;" class="playlms"
                        v-if="i.fileType == 'video'">
                        <img style="width: 100%;height: 100%;" :src="i.converUrl" alt="">
                        <img style="width: 50px;height:50px;position: absolute;z-index: 2;" :src="play" alt="">
                    </div>

                    <div class="de-txt">
                        <div>
                            <span>{{ i.sourceType }}</span>
                        </div>
                        <span style="color: #AAAAAA;">@{{ i.identifyUser }}{{
                            $moment(i.time).format('YYYY-MM-DD')
                        }}</span>
                    </div>
                </div>
            </div>
        </div> -->
        <shade-img v-if="isshade" :msg="moreImg" @closeShade="isshade = false" />
        <!-- <ewm ref="custonEwm" :msg="ode.fungusResource.qrCodeUrl" /> -->
        <!-- 新增修改 -->
        <ha-form ref="haf" @refreshList="getAnimalsInfo()" />
        <!-- 新增修改 -->

        <uploadIs ref="uai" @refreshcar="getAnimalsInfo()" />
        <uploadMapImages ref="umai" @refreshcar="redta" />
        <pre-video ref="lookVideo" />
        <image-carousel ref="ics" :msg="sonO" @closeIc="redsic" v-if="islm" />
    </div>
</template>
<style scoped>
@import '@/assets/css/details.css';
</style>